package com.antdesignbackend.backend.controller;

import com.antdesignbackend.backend.aop.AuthToken;
import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.entity.*;
import com.antdesignbackend.backend.entity.entityVo.UserRoleVo;
import com.antdesignbackend.backend.entity.entityVo.UsersVo;
import com.antdesignbackend.backend.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/event")
public class EventController {

    private Integer userId;
    private String roleID;
    private Integer menuId;
    ReturnVO result = new ReturnVO();

    @Autowired
    UserService userService;
    @Autowired
    ILogService logService;
    @Autowired
    EventplannService eventplannService;
    @Autowired
    EventService eventService;
    @Autowired
    UsereventService usereventService;
    @Autowired
    ReturnformService returnformService;
    @Autowired
    CouponService couponService;

    /**
     * 合伙人报表
     */
    @GetMapping("/memberEvent")
    @AuthToken
    public String memberEvent(String menuId, HttpServletRequest request) {
        this.menuId = Integer.parseInt(menuId);
        //获取cookies信息 roleID 1超级管理员，2管理员，3商户
        userId=(Integer) request.getSession().getAttribute("UserID");
        roleID=(String) request.getSession().getAttribute("RoleID");
        return "event/memberEvent";
    }
    @PostMapping("/tableSearch")
    @ResponseBody
    @AuthToken
    public ReturnVO tableSearch(@RequestBody UserRoleVo userRoleVo) {
        ReturnVO result = new ReturnVO();
        List<UsersVo> datalist=new ArrayList<>();
        QueryWrapper<UsersVo> wrapper =new QueryWrapper<UsersVo>();
        //正常查询过滤条件
        if(userRoleVo.getUserName()!=null && !userRoleVo.getUserName().equals("")){
            wrapper.and(wra -> wra.like("userName", userRoleVo.getUserName()));
        }
        if(userRoleVo.getPhone()!=null && userRoleVo.getPhone()!=""){
            wrapper.and(wra -> wra.eq("phone", userRoleVo.getPhone()));
        }
        //先统计满足条件的数据总数，因为sql 不包括排序
        int total=userService.count(wrapper);
        result.setTotal(total);
        //再查询
        if(total>0){
            datalist= userService.searchs(wrapper.orderByAsc("userName"),new Page<>(userRoleVo.getPageIndex(),userRoleVo.getPageSize()));
        }
        result.setData(datalist);
        return result;
    }
    /***
     * 充值
     * @return
     */
    @PostMapping("/addAmount")
    @ResponseBody
    @AuthToken
    public ReturnVO addAmount(@RequestBody UsersVo vo,HttpServletRequest request) throws Exception {
        result = new ReturnVO();
        String loginName=request.getSession().getAttribute("LoginName").toString();
        boolean b = false;
        Users entity = new Users();
        entity= userService.getById(vo.getUserID());
        Double addAmount=vo.getAmount();
        Double amount=entity.getFrozenAmount()+addAmount;
        entity.setFrozenAmount(amount);
        b=userService.updateById(entity);
        if(b==true){
            result.setMessage("保存成功！");
            result.setCode("200");
            logService.WriteLog(100, "会员"+entity.getUserName()+"充值"+addAmount, loginName);
        }else{
            result.setMessage("保存失败！");
            result.setCode("500");
        }
        return result;
    }
    /***
     * 扣款
     * @return
     */
    @PostMapping("/delAmount")
    @ResponseBody
    @AuthToken
    public ReturnVO delAmount(@RequestBody UsersVo vo,HttpServletRequest request) throws Exception {
        result = new ReturnVO();
        String loginName=request.getSession().getAttribute("LoginName").toString();
        boolean b = false;
        Users entity = new Users();
        entity= userService.getById(vo.getUserID());
        Double delAmount=vo.getAmount();
        Double actAmount=entity.getAmount();
        Double frozenAmount=entity.getFrozenAmount();
        Double totalAmount=entity.getAmount()+entity.getFrozenAmount();
        if(delAmount.compareTo(totalAmount)<=0){
            if(frozenAmount.compareTo(delAmount)>0){
                //空间余额足够扣除
                Double amount=frozenAmount-delAmount;
                entity.setFrozenAmount(amount);
                b=userService.updateById(entity);
            }else {
                //空间余额不足扣除，提现金额来补
                Double cenAmount=delAmount-frozenAmount;
                Double amount=actAmount-cenAmount;
                entity.setFrozenAmount(0.0);
                entity.setAmount(amount);
                b=userService.updateById(entity);
            }
        }
        if(b==true){
            result.setMessage("保存成功！");
            result.setCode("200");
            logService.WriteLog(100, "会员"+entity.getUserName()+"扣款"+delAmount, loginName);
        }else{
            result.setMessage("保存失败！");
            result.setCode("500");
        }
        return result;
    }
    /***
     * 参与活动
     * @return
     */
    @PostMapping("/actEvent")
    @ResponseBody
    @AuthToken
    public ReturnVO actEvent(@RequestBody UsersVo vo,HttpServletRequest request) throws Exception {
        result = new ReturnVO();
        String loginName=request.getSession().getAttribute("LoginName").toString();
        boolean b = false;
        if(vo.getId().equals(78)){
            QueryWrapper<Event> wrapper =new QueryWrapper<Event>();
            wrapper.eq("eventId",vo.getId());
            Event event=eventService.getOne(wrapper);
            //存入活动用户关联表
            Userevent userevent=new Userevent();
            userevent.setUserId(vo.getUserID());
            userevent.setEventId(vo.getId());
            userevent.setReturnTimes(event.getFrequency()-1);
            userevent.setIsYear(event.getIsReturn());
            usereventService.save(userevent);
            //存入用户返还表
            Returnform returnform=new Returnform();
            returnform.setUserId(vo.getUserID());
            returnform.setEventId(vo.getId());
            if(event.getIsReturn().equals(1)){
                returnform.setReturnAmount(event.getYearReturn());
            }
            if(event.getIsReturn().equals(2)){
                returnform.setReturnAmount(event.getMonthReturn());
            }
            returnform.setReturnTime(new Date());
            returnform.setOperator(loginName);
            returnformService.save(returnform);
            //立即对用户存入第一次返还金额
            Users users=userService.getById(vo.getUserID());
            if(event.getIsReturn().equals(1)){
                users.setFrozenAmount(users.getFrozenAmount()+event.getYearReturn());
            }
            if(event.getIsReturn().equals(2)){
                users.setFrozenAmount(users.getFrozenAmount()+event.getMonthReturn());
            }
            b=userService.updateById(users);
        }
        if(b==true){
            result.setMessage("保存成功！");
            result.setCode("200");
        }else{
            result.setMessage("保存失败！");
            result.setCode("500");
        }
        return result;
    }
    /**
     * 获得活动列表
     */
    @ResponseBody
    @GetMapping(value = "/getEvent")
    public ReturnVO getServUser(HttpServletRequest request) {
        result = new ReturnVO();
        List<Eventplann> dataList = eventplannService.list();
        result.setData(dataList);
        return result;
    }
    /***
     * 添加优惠券
     * @return
     */
    @PostMapping("/addCoupon")
    @ResponseBody
    public ReturnVO addCoupon(@RequestBody Coupon vo){
        result = new ReturnVO();
        boolean b = false;
        Coupon coupon = new Coupon();
        coupon.setCouponName(vo.getCouponName());
        coupon.setUserId(vo.getUserId());
        coupon.setMoney(vo.getMoney());
        coupon.setAmount(vo.getAmount());
        coupon.setStartTime(vo.getStartTime());
        coupon.setEndTime(vo.getEndTime());
        coupon.setState(0);
        b=couponService.save(coupon);
        if(b==true){
            result.setMessage("保存成功！");
            result.setCode("200");
        }else{
            result.setMessage("保存失败！");
            result.setCode("500");
        }
        return result;
    }


}
